'''
Created on 28/05/2011

@author: Rodrigo Reyes
'''

from configparser import SafeConfigParser
from entrygui import EntryGUI
from crontab import CronTab, Event

class Scheduler(object):
    
    def __init__(self):
        #Try to read the properties file
        properties = "config.properties"
    
        try:
            cfg = SafeConfigParser()
            cfg.read(properties)
            
            options = dict(cfg.items("schedule"))
            enableSchedule = options.get('enableschedule') == 'true'
        except:
            enableSchedule = False
        
        if(not enableSchedule):
            EntryGUI()
        else:
            # Let's parse the rest of the properties
            startTime = int(options.get('starttime'))
            endTime = int(options.get('endtime'))
            daysOfWeek = set(options.get('daysofweek').split(','))
            reminderPeriodInMinutes = int(options.get('reminderperiodinminutes'))
            
            # Now, let's generate the crontab options
            hourSet = range(startTime, endTime + 1)
            minuteSet = range(0, 60, reminderPeriodInMinutes)
            weekDaySet = set()
            for dow in daysOfWeek:
                weekDaySet.add(int(dow))
            
            #Starting the crontab
            self.cronTab = CronTab(
                        Event(EntryGUI, minuteSet, hourSet, dow=weekDaySet),
            )
            self.cronTab.start()
            
    def stop(self):
        try:
            self.cronTab.stop = True
        except:
            pass